#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  storage.py
#  description

#  Created by zhouzongli633 on 2020/6/4 9:14 上午.
#  Copyright ©Intellectus All rights reserved.

from Common.Storage_Blob_Manager import StorageManage
from Common.decorators import check_param, check_token, method
from Common.logger import app_log
from Common.response import resp
from NICU2HOME import settings
import json
from django.http import HttpResponse
from Common.utils import CommonUtil


@check_token()
@check_param(['file_name'])
@method('GET')
def get_SAS_token(request):
    try:
        name = request.GET.get('file_name')
        data = {}
        year_month = CommonUtil.get_now_time_string('%Y_%m')
        time_stamp = CommonUtil.get_now_time_timestamp()

        file_name = "{}/{}_{}".format(year_month, time_stamp, name)
        image_path = "{}/{}/{}".format(settings.STORAGE_ACCOUNT_URL, settings.STORAGE_CONTAINER_NAME, file_name)

        manager = StorageManage()
        sas_t = manager.get_shared_access_signature()
        data['sas_token'] = sas_t
        data['upload_ual'] = image_path

        return resp(0, data)
    except Exception as e:
        app_log.exception(e)
        return resp(-1)


@method('POST')
def upload_file(request):
    try:
        file = request.FILES.get("upload", None)  # 获取上传的文件，如果没有文件，则默认为None
        name = file.name
        content_type = file.content_type
        if not file:
            return resp(4002)

        year_month = CommonUtil.get_now_time_string('%Y_%m')
        time_stamp = CommonUtil.get_now_time_timestamp()

        file_name = "{}/{}_{}".format(year_month, time_stamp, name)
        manager = StorageManage()
        manager.upload_file(file, file_name, content_type=content_type)
        image_path = "{}/{}/{}".format(settings.STORAGE_ACCOUNT_URL, settings.STORAGE_CONTAINER_NAME, file_name)

        return HttpResponse(json.dumps({"uploaded": 1, "url": image_path}))

    except Exception as e:
        app_log.exception(e)
        return resp(-1)


@method('POST')
def delete_file(request):
    try:
        body_json = json.loads(request.body)
        file_url = body_json['file_url']

        blob_name = file_url.split(settings.STORAGE_CONTAINER_NAME + '/')[-1]
        StorageManage().delete_file(blob_name)
        return resp(0)

    except Exception as e:
        app_log.exception(e)
        return resp(-1)
